<script setup name="publishinform">
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import OAMain from '@/components/OAMain.vue';
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElMessage } from 'element-plus';
import staffHttp from '@/api/staffHttp';
import { useAuthStore } from '@/stores/auth';
import informHttp from '@/api/informHttp';
import { useRouter } from 'vue-router';

const router = useRouter()
const authStore = useAuthStore()
const formRef = ref(null)
let departments = ref([])
let informForm = ref({
    title: "",
    content: "",
    department_ids: []
})

const rules = ref({
    title: [{ required: true, message: "请输入标题", trigger: 'blur' }],
    content: [{ required: true, message: "请输入内容", trigger: "blur" }],
    department_ids: [{ required: true, message: "请选择部门", trigger: 'change' }]
})

onMounted(async () => {
    try {
        let res = await staffHttp.getAllDepartment()
        departments.value = res.results
    } catch (err) {
        console.error('完整错误对象:', err)
        ElMessage.error(err.response?.data?.message || err.message)
    }
})

const onSubmit = () => {
    formRef.value.validate(async (valid, fields) => {
        if (valid) {
            try {
                let res = await informHttp.publishInform(informForm.value)
                router.push({name:'inform_list'})
            } catch (err) {
                console.error('完整错误对象:', err)
                ElMessage.error(err.response?.data?.message || err.message)
            }
        }
    })
}

//......这是富文本编辑器......
let mode = "default"
const editorRef = shallowRef()
const toolbarConfig = {}
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            server: import.meta.env.VITE_BASE_URL + '/image/upload',
            fieldName: 'image',
            maxFileSize: 0.5 * 1024 * 1024,
            maxNumberOfFiles: 10,
            allowedFileTypes: ['image/*'],
            headers: {
                Authorization: "JWT" + " " + authStore.token
            },
            timeout: 6 * 1000,
            customInsert(res, insertFn) {
                if (res.errno == 0) {
                    let data = res.data
                    let url = import.meta.env.VITE_BASE_URL + data.url
                    let href = import.meta.env.VITE_BASE_URL + data.href
                    let alt = data.alt
                    insertFn(url, alt, href)
                } else {
                    ElMessage.error(res.message)
                }
            },
            onFailed(file, res) {
                console.log(`${file.name} 上传失败`, res)
            },
            onError(file, err, res) {
                if (file.size > 0.5 * 1024 * 1024) {
                    ElMessage.error('图片文件最大不能超过0.5MB')
                } else {
                    ElMessage.error('图片格式不正确')
                }
            },
        },


    }

}
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor
}
//......这是富文本编辑器......  
</script>

<template>

    <OAMain title="发布通知">
        <el-card class="main_card">
            <el-form :model="informForm" :rules="rules" ref="formRef">
                <el-form-item label="标题" prop="title" placeholder="请输入标题" label-width="100px">
                    <el-input v-model="informForm.title" autocomplete="off" />
                </el-form-item>
                <el-form-item label="部门可见" prop="department_ids" label-width="100px">
                    <el-select multiple v-model="informForm.department_ids" placeholder="请选择可见部门">
                        <el-option :value="0" label="所有部门" />
                        <el-option v-for="department in departments" :label="department.name" :value="department.id"
                            :key="department.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="请输入内容" prop="content" label-width="100px">
                    <div style="border: 1px solid #ccc; width: 100%;">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" :mode="mode" />
                        <Editor style="height: 500px; overflow-y: hidden;" v-model="informForm.content"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                    </div>
                </el-form-item>
                <el-form-item>
                    <div class="onSubmit">
                        <el-button type="primary" @click="onSubmit">确认提交</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-card>
    </OAMain>

</template>

<style scoped>
.main_card {
    margin-top: 20px;
}

.onSubmit {
    text-align: right;
    flex: 1;
    margin-right: 30px;
}
</style>